package com.sky.zzh.today;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.utils.ValueFormatter;
import com.next.intf.ITaskListener;
import com.next.net.SHGet;
import com.next.net.SHTask;
import com.sky.widget.SHDialog;
import com.sky.zzh.R;
import com.sky.zzh.util.CommonUtil;
import com.sky.zzh.util.ConfigDefinition;
import com.sky.zzh.util.UserInfoManager;

/**
 * 今日数据
 * 
 * @author steveyan
 *
 */
public class TurnFragment extends IFragment implements ITaskListener {

  // 常量
  private static final String PARAM_STARTHOUR = "param1";
  private static final String PARAM_ENDHOUR = "param2";
  private static final String PARAM_STARTDATE = "param3";
  private static final String PARAM_ENDDATE = "param4";

  // 接收的参数
  private int type;
  private String date;

  // fragment和activity的通信接口
  private OnFragmentInteractionListener mListener = null;

  private LineChart mChart;

  // X轴显示的内容
  private ArrayList<String> xVals;

  public TurnFragment() {}

  private SHGet turnUpTask;
  private String today = "2015-09-24";
  private String currentSelectDate = "2015-09-24";
  private String fromDate, endDate;
  private Calendar calendar;
  private int startHour, endHour;
  MyValueFormatter customValueFormatter;
  MyYValueFormatter mMyYValueFormatter = new MyYValueFormatter();

  // /
  private HashMap<Integer, Integer> allAvailableData = new HashMap<Integer, Integer>();

  //
  public static TurnFragment newInstance(int startHour, int endHour, String startDate,
      String endDate) {
    TurnFragment fragment = new TurnFragment();
    Bundle args = new Bundle();
    args.putInt(PARAM_STARTHOUR, startHour);
    args.putInt(PARAM_ENDHOUR, endHour);
    args.putString(PARAM_STARTDATE, startDate);
    args.putString(PARAM_ENDDATE, endDate);
    fragment.setArguments(args);
    return fragment;
  }



  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
      startHour = getArguments().getInt(PARAM_STARTHOUR);
      endHour = getArguments().getInt(PARAM_ENDHOUR);
      fromDate = getArguments().getString(PARAM_STARTDATE);
      endDate = getArguments().getString(PARAM_ENDDATE);
    } else {
      startHour = 6;
      endHour = 4;
    }
    calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH) + 1;
    int day = calendar.get(Calendar.DAY_OF_MONTH);
    today = year + "" + CommonUtil.getDoubleNum(month) + "" + CommonUtil.getDoubleNum(day);
    currentSelectDate = endDate;
  }

  @Override
  public void onDateChanged(String startDate, String endDate) {
    this.fromDate = startDate;
    this.endDate = endDate;
    // requestData("20150923", "20150924");
    requestData(fromDate, endDate);
  }


  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_turn, container, false);
    mChart = (LineChart) view.findViewById(R.id.linechart);

    // no description text
    mChart.setDescription("");
    // enable value highlighting
    mChart.setHighlightEnabled(true);

    // disenable touch gestures
    mChart.setTouchEnabled(false);

    mChart.setDragDecelerationFrictionCoef(0.9f);

    // enable scaling and dragging
    mChart.setDragEnabled(false);
    mChart.setScaleEnabled(false);
    mChart.setDrawGridBackground(false);
    mChart.setHighlightPerDragEnabled(false);

    // if disabled, scaling can be done on x- and y-axis separately
    mChart.setPinchZoom(false);

    mChart.animateX(2500);

    // get the legend (only possible after setting data)
    Legend l = mChart.getLegend();
    l.setEnabled(false);

    // modify the legend ...
    // l.setPosition(Legend.LegendPosition.LEFT_OF_CHART);
    // l.setForm(Legend.LegendForm.LINE);
    // l.setTextSize(11f);
    // l.setTextColor(Color.WHITE);
    // l.setPosition(Legend.LegendPosition.BELOW_CHART_LEFT);
    // l.setYOffset(11f);

    XAxis xAxis = mChart.getXAxis();
    xAxis.setTextSize(12f);
    xAxis.setDrawGridLines(false);
    xAxis.setDrawAxisLine(false);
    xAxis.setSpaceBetweenLabels(1);
    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
    xAxis.setTextColor(getActivity().getResources().getColor(R.color.color_charttextcolor));

    YAxis leftAxis = mChart.getAxisLeft();
    leftAxis.setDrawGridLines(false);
    leftAxis.setTextColor(getActivity().getResources().getColor(R.color.color_charttextcolor));
    leftAxis.setYOffset(1);
    customValueFormatter = new MyValueFormatter(leftAxis);
    leftAxis.setValueFormatter(customValueFormatter);
    leftAxis.setShowOnlyMinMax(true);

    YAxis rightAxis = mChart.getAxisRight();
    rightAxis.setEnabled(false);
    // rightAxis.setTextColor(Color.RED);
    // rightAxis.setAxisMaxValue(900);
    // rightAxis.setStartAtZero(false);
    // rightAxis.setAxisMinValue(-200);
    // rightAxis.setDrawGridLines(false);
    rightAxis.setValueFormatter(mMyYValueFormatter);

    requestData(fromDate, endDate);

    return view;
  }


  private void setData() {
    ArrayList<String> xVals = new ArrayList<String>();
    ArrayList<Entry> yVals1 = new ArrayList<Entry>();
    int value = 0;
    if (endHour > startHour) {
      for (int i = startHour, j = 0; i <= endHour; i += 1, j++) {
        xVals.add(i + "");
        if (allAvailableData.containsKey(i)) {
          value = allAvailableData.get(i);
        } else {
          value = 0;
        }
        yVals1.add(new Entry(value, j));
      }
    } else {
      int j = 0;
      for (int i = startHour; i <= 24; i += 1, j++) {
        xVals.add(i + "");
        if (allAvailableData.containsKey(i)) {
          value = allAvailableData.get(i);
        } else {
          value = 0;
        }
        yVals1.add(new Entry(value, j));
      }
      for (int i = 1; i <= endHour; i++, j++) {
        xVals.add(i + "");
        if (allAvailableData.containsKey(i)) {
          value = allAvailableData.get(i);
        } else {
          value = 0;
        }
        yVals1.add(new Entry(value, j));
      }
    }
    // create a dataset and give it a type
    LineDataSet set1 = new LineDataSet(yVals1, "DataSet 1");
    set1.setAxisDependency(YAxis.AxisDependency.LEFT);
    set1.setColor(getActivity().getResources().getColor(R.color.color_chartlinecolor));
    set1.setCircleColor(Color.WHITE);
    set1.setLineWidth(2f);
    set1.setCircleSize(3f);
    set1.setFillAlpha(65);
    set1.setFillColor(getActivity().getResources().getColor(R.color.color_chartlinecolor));
    set1.setHighLightColor(Color.rgb(244, 117, 117));
    set1.setDrawCircleHole(false);
    // set1.setFillFormatter(new MyFillFormatter(0f));
    // set1.setDrawHorizontalHighlightIndicator(false);
    // set1.setVisible(false);
    // set1.setCircleHoleColor(Color.WHITE);

    // ArrayList<Entry> yVals2 = new ArrayList<Entry>();
    //
    // for (int i = 0; i < count; i++) {
    // float mult = range;
    // float val = (float) (Math.random() * mult) + 450;// + (float)
    // // ((mult *
    // // 0.1) / 10);
    // yVals2.add(new Entry(val, i));
    // }


    ArrayList<LineDataSet> dataSets = new ArrayList<LineDataSet>();
    dataSets.add(set1); // add the datasets

    // create a data object with the datasets
    LineData data = new LineData(xVals, dataSets);
    data.setValueTextColor(Color.WHITE);
    data.setValueTextSize(9f);
    data.setValueFormatter(mMyYValueFormatter);
    // set data
    mChart.setData(data);
  }

  private void requestData(String fromDate, String endDate) {
    SHDialog.dismissProgressDiaolg();
    if (turnUpTask != null) {
      turnUpTask.cancel(true);
    }
    SHDialog.ShowProgressDiaolg(getActivity());
    turnUpTask = new SHGet();
    turnUpTask.setListener(this);
    if (currentSelectDate.equals(today)) {
      turnUpTask.setUrl(ConfigDefinition.URL + "app/SensorDataToday");
      turnUpTask.getTaskArgs().put("UUID", UserInfoManager.getInstance().getUUID());
      // turnUpTask.getTaskArgs().put("UUID", "MT003");
      turnUpTask.getTaskArgs().put("UserId", UserInfoManager.getInstance().getUserId());
      turnUpTask.getTaskArgs().put("DataProperty", "1");
    } else {
      StringBuffer sb = new StringBuffer();
      sb.append(ConfigDefinition.URL);
      sb.append("app/SensorDataHistory?UUID=");
      sb.append(UserInfoManager.getInstance().getUUID());
      // sb.append("MT003");
      sb.append("&");
      sb.append("DataProperty=1&FromDate=");
      sb.append(fromDate);
      sb.append("&");
      sb.append("EndDate=");
      sb.append(endDate);
      turnUpTask.setUrl(sb.toString());
      // turnUpTask.setUrl(ConfigDefinition.URL + "app/SensorDataHistory");
      // turnUpTask.getTaskArgs().put("UUID", UserInfoManager.getInstance().getUUID());
      // turnUpTask.getTaskArgs().put("UUID", "MT003");
      // turnUpTask.getTaskArgs().put("UserId", UserInfoManager.getInstance().getUserId());
      // turnUpTask.getTaskArgs().put("DataProperty", "1");
      // turnUpTask.getTaskArgs().put("FromDate", fromDate);
      // turnUpTask.getTaskArgs().put("EndDate", endDate);
      // turnUpTask.getTaskArgs().put("FromTime", URLEncoder.encode("06:00"));
      // turnUpTask.getTaskArgs().put("EndTime", URLEncoder.encode("18:00"));
    }
    turnUpTask.start();
  }

  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
  }


  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
      mListener = (OnFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
      throw new ClassCastException(activity.toString()
          + " must implement OnFragmentInteractionListener");
    }
  }

  @Override
  public void onDetach() {
    super.onDetach();
    mListener = null;
  }

  @Override
  public void onTaskFinished(SHTask task) throws Exception {
    JSONObject json = new JSONObject(task.getResult().toString());
    System.out.println("json:ppp" + json);
    int max = 0;
    // 解析出数据来
    if (task == turnUpTask) {
      if ("200".equals(json.optString("ReturnCode"))) {
        try {
          // 传感器的数据
          JSONArray sensorDataJSONArray = json.optJSONArray("SensorData");
          JSONArray array = null;
          JSONObject obj = null;
          // 处理property为1的体动
          for (int i = 0; i < sensorDataJSONArray.length(); i++) {
            array = sensorDataJSONArray.getJSONObject(i).optJSONArray("Data");
            int property = sensorDataJSONArray.getJSONObject(i).optInt("PropertyCode");
            if (property != 1) {
              continue;
            }
            for (int j = 0; j < array.length(); j++) {
              obj = array.getJSONObject(j);
              int index = getHourFromTime(obj.optString("At"));
              int value = obj.optInt("Value");
              if (allAvailableData.containsKey(index)) {
                value += allAvailableData.get(index);
              }
              max = max > value ? max : value;
              allAvailableData.put(index, value);
            }
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
        mChart.getAxisLeft().setAxisMaxValue(max);
      }
      setData();
      SHDialog.dismissProgressDiaolg();
    }
  }

  // 返回小时
  private int getHourFromTime(String s) {
    String[] split = s.split(" ");
    String[] split2 = split[1].split(":");
    return Integer.valueOf(split2[0]);
  }


  @Override
  public void onTaskFailed(SHTask task) {}



  @Override
  public void onTaskUpdateProgress(SHTask task, int count, int total) {}



  @Override
  public void onTaskTry(SHTask task) {}



}
